import os
import LoadDataControl
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QDialog
from Ui.DownDataControl import Ui_Dialog_DownDataControl
from subprocess import run
import numpy as np
from datetime import datetime, timedelta


class DownDataControl(QDialog, Ui_Dialog_DownDataControl):
    finish = pyqtSignal()

    def __init__(self):
        super(DownDataControl, self).__init__()
        self.setupUi(self)
        self.path = os.getcwd()
        self.data_path = self.path + '\\datadown\\data'  # bin文件 保存路径
        self.file = self.path + '\\datadown\\bin_down.exe'
        self.sum_data = None

    def InitDialog(self):
        time_now = datetime.now().replace(second=0, microsecond=0) + timedelta(minutes=1)
        time_diff = timedelta(minutes=-2)
        self.dateTimeEdit_start.setDateTime(time_now + time_diff)
        self.dateTimeEdit_end.setDateTime(time_now)

    def ThreadStart(self):
        start = self.dateTimeEdit_start.dateTime().toMSecsSinceEpoch()
        end = self.dateTimeEdit_end.dateTime().toMSecsSinceEpoch()
        self.DownLoadData(start, end)
        self.finish.emit()

    def DownLoadData(self, start, end):
        run([self.file, str(start), str(end)], shell=True)
        try:
            files = os.listdir(self.data_path)
            if len(files) > 0:
                new_path = os.path.join(self.data_path, files[0])
                files = os.listdir(new_path)
                sum_data = [None, None, None, None]
                for i in range(len(files)):
                    ch = int(files[i].split('_')[1][1]) - 1
                    if sum_data[ch] is None:
                        sum_data[ch] = LoadDataControl.LoadSingleFile(os.path.join(new_path, files[i]))
                        pass
                    else:
                        sum_data[ch] = np.hstack((sum_data[ch], LoadDataControl.LoadSingleFile(os.path.join(new_path, files[i]))))
                    os.remove(os.path.join(new_path, files[i]))
                os.rmdir(new_path)
                for i in range(4):
                    if i == 0:
                        self.sum_data = sum_data[i]
                    else:
                        self.sum_data += sum_data[i]
        except:
            pass
